package com.bkitmobile.kesu.android.ClassInfo;

import java.util.LinkedList;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.bkitmobile.kesu.android.GUI.R;

public class PlaceAdapter extends ArrayAdapter<PlaceShortInfo>{
	private Context context;
	private LinkedList<PlaceShortInfo> objects;
	private double lng, lat;
	private Location myLoc;
	
	public PlaceAdapter(Context context, LinkedList<PlaceShortInfo> objects, double lat, double lng) {
		super(context, R.layout.search_list_item, objects);
		this.context = context;
		this.objects = objects;
		myLoc = new Location("reverseGeocoded");
		myLoc.setLatitude(lat);
		myLoc.setLongitude(lng);
		this.lng = lng;
		this.lat = lat;
	}
	public View getView(int position,  View convertView, ViewGroup parent) {
		View item = convertView;
		Log.d("GetView", "" + position);
		if(item == null){
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			item = inflater.inflate(R.layout.search_list_item, null);
		}
		TextView txtType, txtName, txtAddr, txtDistance;
		txtType = (TextView) item.findViewById(R.id.search_list_item_type);
		txtName = (TextView) item.findViewById(R.id.search_list_item_name);
		txtAddr = (TextView) item.findViewById(R.id.search_list_item_address);
		txtDistance = (TextView) item.findViewById(R.id.search_list_item_distance);
		
		PlaceShortInfo object = objects.get(position);
		txtType.setText(((Activity)context).getString(R.string.search_string_type)+ " " + object.getType());
		txtName.setText(((Activity)context).getString(R.string.search_string_name)+ " " + object.getName());
		txtAddr.setText(((Activity)context).getString(R.string.search_string_addr)+ " " + object.getAddress());
		if(object.getDist().equals(""))
			object.setDist(computeDistance(object.getLongtitude(), object.getLatitude()));
		
		txtDistance.setText(((Activity)context).getString(R.string.search_string_dist)+ " " + object.getDist());
		return item;
	}
	
	private String computeDistance(double pLng, double pLat){
		Location desLoc = new Location("reverseGeocoded");
		desLoc.setLatitude(pLat);
		desLoc.setLongitude(pLng);
		float dist = myLoc.distanceTo(desLoc);
		
		int kmDist = (int) (dist/1000);
		int mDist = (int) (dist%1000);
		String result = "" + (kmDist>0?(kmDist+ "km "):"") + mDist + "m";
		
		return result;
		
	}
	
}
